package com.signway.harmony_demo.devices;

import com.signway.harmony_demo.ResourceTable;
import ohos.agp.components.*;
import ohos.app.Context;
import ohos.distributedschedule.interwork.DeviceInfo;

import java.util.List;
import java.util.Optional;

public class DevicesListAdapter extends BaseItemProvider {
    public static final int SUBSTRING_START = 0;
    public static final int SUBSTRING_END = 4;
    private List<DeviceInfo> deviceInfoList = null;
    private Context context = null;

    public DevicesListAdapter(Context context, List<DeviceInfo> deviceInfoList) {
        this.context = context;
        this.deviceInfoList = deviceInfoList;
    }

    @Override
    public int getCount() {
        return deviceInfoList == null ? 0 : deviceInfoList.size();
    }

    @Override
    public Object getItem(int i) {
        return Optional.of(deviceInfoList.get(i));
    }

    @Override
    public long getItemId(int i) {
        return i;
    }

    @Override
    public Component getComponent(int i, Component component, ComponentContainer componentContainer) {
        ViewHolder viewHolder = null;
        Component mComponent = component;
        if (mComponent == null) {
            mComponent = LayoutScatter.getInstance(context)
                    .parse(ResourceTable.Layout_item_device_list, null, false);
            viewHolder = new ViewHolder();
            viewHolder.devicesName = (Text) mComponent.findComponentById(ResourceTable.Id_device_name);
            viewHolder.devicesId = (Text) mComponent.findComponentById(ResourceTable.Id_device_id);
            mComponent.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) mComponent.getTag();
        }
        if (viewHolder != null) {
            viewHolder.devicesName.setText(deviceInfoList.get(i).getDeviceName());
            String deviceId = deviceInfoList.get(i).getDeviceId();
            deviceId = deviceId.substring(SUBSTRING_START, SUBSTRING_END) + "******"
                    + deviceId.substring(deviceId.length() - SUBSTRING_END);
            viewHolder.devicesId.setText(deviceId);
        }
        return mComponent;
    }

    /**
     * ViewHolder
     *
     * @since 2021-03-12
     */
    private static class ViewHolder {
        private Text devicesName;
        private Text devicesId;
    }
}
